package ms.utils;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;

public class SocketUtil {

	private Socket socket;
	// private BufferedReader inStream;
	// private PrintWriter outStream;
	private ObjectOutputStream out;
	private ObjectInputStream in;

	public SocketUtil(Socket socket) throws IOException {
		this.socket = socket;
		out = new ObjectOutputStream(socket.getOutputStream());
		in = new ObjectInputStream(socket.getInputStream());
	}

	public String readString() throws IOException {
		String result = null;
		synchronized (in) {
			result = in.readUTF();
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public <T extends Serializable> T readObject() throws IOException {
		T result = null;
		synchronized (in) {
			try {
				result = (T) in.readObject();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public void writeString(String value) throws IOException {
		synchronized (out) {
			out.writeUTF(value);
			out.flush();
		}
	}

	public void writeString(String pattern, Object... args) throws IOException {
		synchronized (out) {
			out.writeUTF(String.format(pattern, args));
			out.flush();
		}
	}

	public void writeObject(Serializable object) throws IOException {
		synchronized (out) {
			out.writeObject(object);
			out.reset();
		}
	}

	public boolean isAvailable() {
		return socket.isConnected() && !socket.isInputShutdown();
	}

	public void close() throws IOException {
		socket.close();
	}
}
